package org.ming.ticketSellingSystem.framework.starter.bases;

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

public class Singleton {
    private static final ConcurrentHashMap<String,Object> SINGLE_OBJECT_POOL = new ConcurrentHashMap<>();

    /**
     * get singleton (T)obj By Key
     * @param key
     * @return
     * @param <T>
     */
    public static <T> T get(String key) {
        Object obj = SINGLE_OBJECT_POOL.get(key);
        return obj == null ? null : (T) obj;
    }

    /**
     * get singleton (T)obj By Key
     * if res == null AND supplier.get()!=null
     *      res will put HashMap
     * @param key
     * @param supplier
     * @return
     * @param <T>
     */
    public static <T> T get(String key, Supplier<T> supplier){
        Object res = SINGLE_OBJECT_POOL.get(key);
        if(res == null && (res = supplier.get()) != null)
            SINGLE_OBJECT_POOL.put(key,res);
        return res == null ? null : (T) res;
    }

    /**
     * put obj to HashMap
     * @param obj
     */
    public static void put(Object obj){
        put(obj.getClass().getName(),obj);
    }

    /**
     * put (key,obj) to HashMap
     * @param key
     * @param obj
     */
    public static void put(String key,Object obj){
        SINGLE_OBJECT_POOL.put(key,obj);
    }


}
